"use strict";

import {
  config,
  dbData,
  main,
  session,
  utils
} from "./instances";

const dbGet = Rokid.promisify(Rokid.dbServer.get);
const dbSet = Rokid.promisify(Rokid.dbServer.set);

/**
 * @class DBData 持久化数据
 */
class DBData {
  /**
   * @method constructor
   */
  constructor() {
    this._status = {}; //是否已经加载状态
    this._data = {};
  }

  checkZone(zone) {
    if (!this._data.hasOwnProperty(zone)) {
      this._data[zone] = {};
    }
  }

  set(zone, key, val) {
    this.checkZone(zone);
    this._data[zone][key] = val;
    return val;
  }

  get(zone, key, def = null) {
    this.checkZone(zone);
    if (this._data[zone].hasOwnProperty(key)) {
      return this._data[zone][key];
    }
    this._data[zone][key] = def;
    return def;
  }

  recoverZone(zone, data) {
    this._data[zone] = data;
  }

  // 从数据库恢复保存的数据，手动调用
  reload(zone = "data") {
    let self = this;
    let err = null;
    return new Promise((resolve, reject) => {
      if (!self._loaded) {
        self._loaded = true;
        let dbKey = [main.getUserID(), zone].join("_");
        return dbGet(dbKey).then(result => {
          if (result.length > 2 || result != "未查询到相关数据") {
            try {
              self.recoverZone(zone, JSON.parse(result));
            } catch (e) {
              console.debug("[DEBUG]", e);
              err = e;
            }
            console.debug(
              "[DBReloadResult]",
              JSON.stringify({
                db_key: dbKey,
                data: self._data
              })
            );
          }
          resolve(this._data[zone]);
        });
      } else {
        resolve(this._data[zone]);
      }
    });
  }

  // 提交数据到数据库
  submit() {
    let self = this;
    return new Promise((resolve, reject) => {
      let stack = [];
      for (const zone in self._data) {
        if (self._data.hasOwnProperty(zone)) {
          let val = self._data[zone];
          let dbKey = [main.getUserID(), zone].join("_");
          stack.push(dbSet(dbKey, JSON.stringify(val)).then(res => {
            console.debug("[DBSubmit RES]", res);
            return res;
          }));
        }
      }
    });
  }

  // 清空记录
  clearUpItems() {
    this._data = {
      record_count: 0,
      record_first: "",
      record_last: "",
      records: {}
    };
  }
}

export default DBData;
